//
//  CoinTransView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/5.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
private let KIdenty = "AssetDetailTableViewCell"
class CoinTransView: BaseView, UITableViewDataSource, UITableViewDelegate {
    var viewModel:CoinTransViewModel?
    var availLabel:UILabel? //可用
    var freeLabel:UILabel? //冻结
    lazy var tableView:UITableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.grouped)
    lazy var headView: UIView = {
       let view = UIView()
        view.frame = CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 155)
        view.backgroundColor = kTitleColor
       return view
    }()
    lazy var useLabel: UILabel = {
        let label = BaseLabel(style: .twiceStyle)
        label.font = UIFont.systemFont(ofSize: 11)
        return label
    }()
    
    lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = UIColor(hexStr: "#e7ebf4")
        return label
    }()
    lazy var moneyLabel:UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = UIColor(hexStr: "#757b86")
        return label
    }()
    lazy var selectBtn:UIButton = {
        let btn =  CommonBtn.creatSelectBtnWithTitle(title: kText("划出"), y: 60, view: self, sel:  #selector(selectBtnAction))
        return btn
    }()
    
    lazy var layOffBtn:UIButton = {
        let btn =  CommonBtn.creatSelectBtnWithTitle(title: kText("划入"), y: 60, view: self, sel:  #selector(layOffBtnAction))
        return btn
    }()
    
    lazy var footView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 100))
        return view
    }()
    
    override func setUpUI() -> Void {
        viewModel = dataSource as? CoinTransViewModel
        
        //注册监听
        self.viewModel?.addObserver(self, forKeyPath: "totalMoney", options: [.new,.old], context: nil)
        //注册监听
        self.viewModel?.addObserver(self, forKeyPath: "refreshBool", options: [.new,.old], context: nil)
        
        
        self.addSubview(tableView)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.register(UINib(nibName: KIdenty, bundle: nil), forCellReuseIdentifier: KIdenty)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.clear
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.top.equalToSuperview()
        }
        tableView.tableHeaderView = headView
        tableView.creatEmptyView()
        
        headView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(27)
            make.centerX.equalToSuperview()
        }
        
        headView.addSubview(moneyLabel)
        moneyLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(73)
            make.centerX.equalToSuperview()
        }
        
        for i in 0..<2 {
            let availLabel = UILabel()
            availLabel.font = UIFont.systemFont(ofSize: 11)
            availLabel.textColor = kContrnColor
            availLabel.text = i==0 ? kText("可用") : kText("冻结")
            headView.addSubview(availLabel)
            availLabel.snp.makeConstraints { (make) in
                make.top.equalToSuperview().offset(107)
                make.left.equalToSuperview().offset(i==0 ? 50.00 : kSCREEN_WIDTH/2+50)
            }
            
            let numberLabel = UILabel()
            numberLabel.font = UIFont.systemFont(ofSize: 13)
            numberLabel.textColor =  kContrnColor
            numberLabel.text = "0.2343432432"
            if i == 0 {
                self.availLabel = numberLabel
            }else {
                self.freeLabel = numberLabel
            }
            headView.addSubview(numberLabel)
            numberLabel.snp.makeConstraints { (make) in
                make.left.equalTo(availLabel)
                make.top.equalTo(availLabel.snp.bottom).offset(10)
            }
        }
        if viewModel?.type != .coinType  {
            tableView.snp.updateConstraints{ (make) in
                make.bottom.equalToSuperview().offset(isiPhoneX() ? -94 : -60)
            }
        self.addSubview(footView)
            footView.snp.makeConstraints { (make) in
                make.bottom.equalToSuperview().offset(isiPhoneX() ? -44 : -10)
                make.left.right.equalToSuperview()
                make.height.equalTo(40)
            }
        footView.addSubview(selectBtn)
            selectBtn.snp.makeConstraints { (make) in
                make.top.equalToSuperview().offset(0)
                make.left.equalToSuperview().offset(20)
                make.height.equalTo(40)
                make.width.equalTo((kSCREEN_WIDTH-60)/2)
            }
          footView.addSubview(layOffBtn)
            layOffBtn.snp.makeConstraints { (make) in
                make.top.equalToSuperview().offset(0)
                make.left.equalToSuperview().offset(40+(kSCREEN_WIDTH-60)/2)
                make.height.equalTo(40)
                make.width.equalTo((kSCREEN_WIDTH-60)/2)
            }
        }

    }
    
    
    func setModel()  {
        nameLabel.text = String(format: "%@ %@", CYCalculate.cy_intercept(number: (viewModel?.model.currentAmount)!, digit: (viewModel?.model.coinPrecision)!)!,(viewModel?.model.coinCode)!)
        nameLabel.changeLabelTextStyle(title: CYCalculate.cy_intercept(number: (viewModel?.model.currentAmount)!, digit: (viewModel?.model.coinPrecision)!)!, color: nameLabel.textColor, font: UIFont.systemFont(ofSize: 36))
        
        moneyLabel.text = String(format:"≈ %@ %@",(viewModel?.totalMoney)!,AppCacheInfo.default.currency)
        
        self.availLabel?.text = CYCalculate.cy_intercept(number: (viewModel?.model.currentAmount)!, digit: (viewModel?.model.coinPrecision)!)
        self.freeLabel?.text = CYCalculate.cy_intercept(number: (viewModel?.model.frozenAmount)!, digit: (viewModel?.model.coinPrecision)!)
        
    }
    
    /// KVO监听属性
    ///
    /// - Parameters:
    ///   - keyPath: 被监听的属性名
    ///   - object:
    ///   - change:
    ///   - context:
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "totalMoney" {
           moneyLabel.text = String(format:"≈ %@ %@",(viewModel?.totalMoney)!,AppCacheInfo.default.currency)
        }
        
        if keyPath == "refreshBool" {
            tableView.reloadData()
        }
        
    }
    
    //MARK tableViewDelegate
    
    //MARK tableViewDelegate
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return (viewModel?.dataModel.list.count)!
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: KIdenty, for: indexPath) as! AssetDetailTableViewCell
//        cell.contentView.themeBackground = ThemeManager.ThemeColorKeys.background
//        cell.selectedBackgroundView = UIView(frame: self.bounds)
//        cell.selectedBackgroundView?.themeBackground = ThemeManager.ThemeColorKeys.selectTabColor
        let model = viewModel?.dataModel.list[indexPath.row]
        if model != nil {
            cell.setModel(model: model!, type: (viewModel?.type)!)
            cell.selectionStyle = .none
        }
       
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 115
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 40
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 40))
        view.backgroundColor = UIColor.clear
        
        let recordLabel = UILabel()
        recordLabel.font = UIFont.systemFont(ofSize: 12)
        recordLabel.textColor  = UIColor(hexStr: "#757b86")
        recordLabel.text = kText("最新的3条记录")
        view.addSubview(recordLabel)
        recordLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(16)
        }
        
        let allBtn = UIButton()
        allBtn.setTitle(kText("全部"), for: UIControlState.normal)
        allBtn.setTitleColor(UIColor(hexStr: "#757b86"), for: UIControlState.normal)
        allBtn.addTarget(self, action: #selector(allBtnAction), for: UIControlEvents.touchUpInside)
        allBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        view.addSubview(allBtn)
        allBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-16)
            make.centerY.equalToSuperview()
        }
        
        
        return view
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
    }
    
    @objc func selectBtnAction() {
        if !AppSecurityInfo.default.model.isTradePwd {
            CYMBShow.showMessage(kText("请先设置交易密码"))
            return
        }
        if !self.chekSupport() {
            CYMBShow.showMessage(kText("当前币种不支持划转操作"))
            return
        }
        let controller = TransferViewController()
        controller.viewModel?.model = (viewModel?.model)!
        controller.viewModel?.sendCoin = (viewModel?.type)!
        controller.viewModel?.receiveCoin = .coinType
        self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
    }
    @objc func layOffBtnAction() {
        if !AppSecurityInfo.default.model.isTradePwd {
            CYMBShow.showMessage(kText("请先设置交易密码"))
            return
        }
        if !self.chekSupport() {
            CYMBShow.showMessage(kText("当前币种不支持划转操作"))
            return
        }
        let controller = TransferViewController()
        controller.viewModel?.model = (viewModel?.model)!
        controller.viewModel?.receiveCoin = (viewModel?.type)!
        controller.viewModel?.sendCoin = .coinType
        self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
    }
    
    func chekSupport() -> Bool{
        if viewModel?.type != .legalType {
            return true
        }
        let isHave = false
        if viewModel?.type == .legalType {
            for model in APPAssetInfo.default.coninKidArray {
                if viewModel?.model.coinCode == model.coinCode {
                    return true
                }
            }
        }
        return isHave
    }
    
    @objc func allBtnAction() {
        let controller = AssetDetailViewController()
        controller.viewModel?.type = viewModel?.type
        controller.viewModel?.model = (viewModel?.model)!
        self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
    }
    deinit {
        self.viewModel?.removeObserver(self, forKeyPath: "totalMoney", context: nil)
        self.viewModel?.removeObserver(self, forKeyPath: "refreshBool", context: nil)
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
